package de.pharmacontrol.psa.beans;

import java.sql.Timestamp;
import java.util.Collection;

import javax.ejb.Singleton;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import de.pharmacontrol.pilot.entities.Order;
import de.pharmacontrol.psa.beans.interfaces.OrderService;

@Singleton
public class OrderServiceBean implements OrderService {

	@PersistenceContext(unitName = "pilot")
	protected EntityManager em;

	@Override
	public Order findOrderByName(String name) {
		try {
			return em.createQuery("SELECT o FROM Order o WHERE o.name = :name", Order.class).setParameter("name", name).getSingleResult();
		} catch (NoResultException nre) {
			return null;
		}
	}

	@Override
	public Order updateOrder(Order order) {
		Order merged = em.merge(order);
		em.refresh(merged);
		return merged;
	}

	@Override
	public boolean removeOrder(Order order) {
		if (order != null) {
			Order mergedOrder = em.merge(order);
			em.refresh(mergedOrder);
			if (mergedOrder.getStatus() > 1) {
				return false;
			}
			em.remove(mergedOrder);
			return true;
		}
		return false;
	}

	@Override
	public Order mergeOrder(Order order) {
		return em.merge(order);
	}

	@Override
	public Collection<Order> findOrderByCreateTime(Timestamp start, Timestamp end) {
		TypedQuery<Order> q = em.createQuery("SELECT o FROM Order o WHERE o.created BETWEEN :start AND :end", Order.class);
		q.setParameter("start", start);
		q.setParameter("end", end);
		return q.getResultList();
	}

	@Override
	public void addOrder(Order order) {
		em.persist(order);
	}

}
